const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const { ProvidePlugin } = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { merge } = require("webpack-merge");
const devConfig = require("./dev.config");
const prodConfig = require("./prod.config");

const getCommonConfig = function (isProdution) {
  return {
    entry: "./src/main.js",
    output: {
      clean: true,
      path: path.resolve(__dirname, "../build"),
      filename: "js/[name]_chunk.js",
      // 单独针对分包的文件进行命名
      chunkFilename: "js/[name]_chunk.js",
    },
    resolve: {
      extensions: [".js", ".json", ".wasm", ".jsx", ".ts"],
    },
    module: {
      rules: [
        {
          test: /\.jsx$/,
          use: {
            loader: "babel-loader",
          },
        },
        {
          test: /\.js$/,
          use: "babel-loader",
        },
        {
          test: /\.css$/,
          use: [
            // 'style-loader' // 将css文件变成style标签插入到html文件中, 开发阶段
            isProdution ? MiniCssExtractPlugin.loader : "style-loader", // 将css文件变成style标签插入到html文件中, 生产阶段
            "css-loader", // 将css文件变成commonjs模块加载到js文件中
          ],
        },
      ],
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: "./index.html", // 模板文件
      }),
      new ProvidePlugin({
        axios: ["axios", "default"],
        // get: ['axios', 'get'],
        dayjs: "dayjs",
      }),
    ],
  };
};

// webpack允许导出一个函数
module.exports = function (env) {
  const isProdution = env.production;
  let mergeConfig = isProdution ? prodConfig : devConfig;
  return merge(getCommonConfig(isProdution), mergeConfig);
};
